package com.hust360.percent.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Area;
import com.hust360.percent.pojo.AreaDAO;
import com.hust360.percent.pojo.DiscountInfo;
import com.hust360.percent.pojo.DiscountInfoDAO;
import com.hust360.percent.pojo.Shop;
import com.hust360.percent.pojo.ShopDAO;
import com.hust360.percent.utils.ActivityUtils;
import com.hust360.percent.utils.StorageUtils;

public class FirstRunActivity extends Activity {

	PercentApplication application;
	SharedPreferences sharedPreferences;
	ShopDAO shopDAO;
	DiscountInfoDAO discountInfoDAO;
	SQLiteDatabase citydb;
	AreaDAO areaDAO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityUtils.addActivity(this);
		TextView textView = new TextView(this);
		// textView.setText("the first time app lauch on this device");
		setContentView(textView);

		application = (PercentApplication) getApplication();
		sharedPreferences = application.getSharedPreferences();
		shopDAO = application.getShopDao();
		discountInfoDAO = application.getDiscountInfoDAO();
		areaDAO = application.getAreaDAO();
		/*
		 * 启动另外的线程对数据库进行插入操作插入测试用的数据
		 */
		HandlerThread handlerThread = new HandlerThread("db init");
		handlerThread.start();
		final AppInitHander hander = new AppInitHander(this,
				handlerThread.getLooper());
		hander.post(new Runnable() {
			@Override
			public void run() {

				String shopName = "大洋百货光谷店";
				String shopAddress = "东湖新技术开发区光谷世界城光谷街3号1区101号";
				// String shopTelephone = "(027)87418888";
				Random random = new Random();
				Shop shop = new Shop();
				synchronized (application.getLocalDB()) {

					/*
					 * 创建sd卡文件和文件夹
					 */
					try {
						StorageUtils.buildLocalDataDirectory();
					} catch (IOException e) {
						e.printStackTrace();
					}

					/*
					 * 把包含城市代码和名字等信息的数据库方如程序的独立路径
					 */
					AssetManager assetManager = getAssets();
					OutputStream outputStream;
					InputStream inputStream;
					try {
						inputStream = assetManager.open("city.db");
						File dbFile = new File(
								"//data//data//com.hust360.percent//databases");
						if (!dbFile.isDirectory()) {
							dbFile.mkdir();
						}
						dbFile = new File(
								"//data//data//com.hust360.percent//databases//city.db");
						if (!dbFile.isFile())
							dbFile.createNewFile();
						Log.i("FirstRunActivity",
								"db file path is " + dbFile.getAbsolutePath());
						outputStream = new FileOutputStream(dbFile);
						byte[] buff = new byte[512];
						while (inputStream.read(buff) != -1) {
							outputStream.write(buff);
						}
						inputStream.close();
						outputStream.close();

						citydb = SQLiteDatabase.openDatabase(
								dbFile.getAbsolutePath(), null,
								SQLiteDatabase.OPEN_READONLY);
						application.setCityDB(citydb);

					} catch (IOException e1) {
						e1.printStackTrace();
					}
					
					try {
						InputStream is = getResources().getAssets().open("local_db");
						OutputStream os = new FileOutputStream("/mnt/sdcard/com.hust.percent/local_db");
						byte[] buff = new byte[512];
						while (is.read(buff) != -1){
							os.write(buff);
						}
						
						String[] files = getResources().getAssets().list("/file/");
						for (String str : files) {
							is = getResources().getAssets().open("/file/" + str);
							File f = new File("/mnt/sdcard/file/" + str);
							if (!f.exists()) {
								f.createNewFile();
							}
							os = new FileOutputStream(f);
							while (is.read(buff) != -1){
								os.write(buff);
							}
						}
						
						files = getResources().getAssets().list("/area_file/");
						for (String str : files) {
							is = getResources().getAssets().open("/area_file/" + str);
							File f = new File("/mnt/sdcard/area_file/" + str);
							if (!f.exists()) {
								f.createNewFile();
							}
							os = new FileOutputStream(f);
							while (is.read(buff) != -1){
								os.write(buff);
							}
						}
						
						is.close();
						os.close();
						
					} catch (Exception e) {
						e.printStackTrace();
					}

					/*
					 * 设置程序第一次运行的标志为false
					 */
					Editor edit = sharedPreferences.edit();
					edit.putBoolean(PercentApplication.APP_IS_FIRST_RUN, false);
					edit.commit();

					// // 先获得一个省份和城市的列表
					// Cursor cityc = citydb.query("city", new String[]{"id"},
					// null, null, null, null, null);
					// Long[] cityIds = new Long[cityc.getCount()];
					// int l = 0;
					// while (cityc.moveToNext()) {
					// cityIds[l] = cityc.getLong(0);
					// l++;
					// }
					// cityc.close();
					//
					// /*---------------------------插入100条测试数据-----------------------------------*/
					// // 插入店铺的数据
					// for (int i = 0; i < 1000; i++) {
					// shop.setShopName(shopName + i);
					// shop.setAddress(shopAddress + i);
					// shop.setShopId(StorageUtils.curMaxShopId);
					// shop.setLatitude(90 * random.nextDouble()
					// * (random.nextBoolean() ? 1 : -1));
					// shop.setLongitude(180 * random.nextDouble()
					// * (random.nextBoolean() ? 1 : -1));
					// shop.setTotalRate(random.nextFloat() * 5.0f);
					// shop.setTelephone(random.nextInt(200) + ""
					// + Math.abs(random.nextLong() % 100000000));
					// shop.setBrand(random.nextInt(100000) + "");
					// shop.setCityId(cityIds[random.nextInt(cityIds.length)]);
					// shopDAO.save(shop);
					// StorageUtils.curMaxShopId++;
					// }
					// edit.putLong(StorageUtils.CUR_MAX_SHOP_ID_KEY,
					// StorageUtils.curMaxShopId);
					// edit.commit();
					//
					// String[] filenames;
					// File file = null;
					// try {
					// file = new File(StorageUtils.getSDPath() + "//file//");
					// } catch (IOException e) {
					// e.printStackTrace();
					// }
					// filenames = file.list();
					//
					// // 插入打折信息的测试数据
					// ArrayList<String> imageName = new ArrayList<String>();
					// DiscountInfo info = new DiscountInfo();
					// for (int i = 0; i < 1000; i++) {
					// info.setDiscountInfoId(StorageUtils.curMaxDiscountId);
					// info.setDiscountType(random.nextBoolean() ? 1 : 0);
					// info.setType(random.nextInt(6));
					// info.setDiscount(random.nextInt(11));
					// info.setShopId(Math.abs(random.nextLong()
					// % (StorageUtils.curMaxShopId - 1)));
					// info.setLiked(Math.abs(random.nextLong() % 100000));
					//
					// imageName.clear();
					// int n = random.nextInt(15); //filenames.length
					// int k;
					// for (int j = 0; j < n; j++) {
					// k = random.nextInt(filenames.length);
					// imageName.add(filenames[k]);
					// }
					// info.setDiscountImage(imageName);
					// discountInfoDAO.save(info);
					// StorageUtils.curMaxDiscountId++;
					// }
					//
					// /*插入区域信息测试数据
					// *
					// */
					//
					// Area area = new Area();
					// try {
					// file = new File(StorageUtils.getSDPath() +
					// "//area_file");
					// if (!file.isDirectory())
					// file.mkdir();
					// String[] IMGS = file.list();
					// List<Shop> shopList;
					// List<Long> shopIdList = new ArrayList<Long>();
					// Long city_id;
					// Shop s = new Shop();
					// for (int k = 0; k < 1000; k ++) {
					// area.setId(StorageUtils.curMaxAreaId);
					// area.setTitle("的撒发算去额" + random.nextInt());
					// area.setImg(IMGS[random.nextInt(IMGS.length)]);
					// area.setType(random.nextInt(6));
					// city_id = cityIds[random.nextInt(cityIds.length)];
					// area.setCityId(city_id);
					// s.setCityId(city_id);
					// shopList = shopDAO.findByExample(s);
					// int m = random.nextInt(shopList.size() == 0?1 :
					// shopList.size());
					// for ( ; m > 0; m--)
					// {
					// Shop tmp = shopList.get(random.nextInt(shopList.size()));
					// shopIdList.add(tmp.getShopId());
					// shopList.remove(tmp);
					// }
					// area.setShopList(shopIdList);
					// areaDAO.save(area);
					// }
					// } catch (IOException e) {
					// e.printStackTrace();
					// }
					//
					// edit.putLong(StorageUtils.CUR_MAX_DISCOUNT_ID_KEY,
					// StorageUtils.curMaxDiscountId);
					// edit.commit();
				}
				Message message = hander.obtainMessage();
				message.arg1 = 1;
				hander.sendMessage(message);
			}
		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityUtils.removeActivity(this);
	}

	private static class AppInitHander extends Handler {

		Activity activity;

		private AppInitHander(Activity activity, Looper looper) {
			super(looper);
			this.activity = activity;
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 1) {
				activity.setResult(RESULT_OK);
				Intent intent = new Intent(activity, MainActivity.class);
				activity.startActivity(intent);
				activity.finish();
				this.getLooper().quit();

			}
		}
	}

}
